<template>
    <div class="container-wrapper">
        <el-form :model="question" ref="ruleForm"  class="question-content" label-width="90px" >
            <el-row :gutter="41">
                <el-col :span="12">
                    <div class="form-item-title">
                        <span class="title-level">题目</span>
                    </div>
                    <el-row >
                        <el-col >
                            <el-form-item label="题目内容" prop="content">
                                <Tinymce :toolbar="toolbar" :id="tinymceId2" v-model="question.content" ref="tinymce2" :width="500" :height='160' ></Tinymce>
                                <el-button type="text" @click="insertFormula">插入公式</el-button>
                                <!-- <el-upload
                                    class="upload"
                                    :action="uploadUrl"
                                    :on-success="success"
                                    :on-remove="remove"
                                    >
                                    <el-button type="text">插入图片</el-button>
                                </el-upload> -->
                            </el-form-item>
                        </el-col> 
                    </el-row>
                    <question-check ref="setCheckList" @answer="questionAnswer"></question-check>
                    <div class="form-item-title">
                        <span class="title-level">题目解析</span>
                    </div>
                    <el-row>
                        <el-col>
                            <el-form-item label="解析内容">
                                <div class="question-tit-content">
                                    <Tinymce :toolbar="toolbar" :id="tinymceId3" v-model.trim="question.analysis" ref="tinymce3" :width="500" :height='160' ></Tinymce>
                                </div>
                                <el-button @click="insertFormula1" type="text">插入公式</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <div class="form-item-title">
                        <span class="title-level">知识点</span>
                    </div>
                    <el-row >
                        <el-col>
                            <!-- <el-form-item label="已有知识点" prop="knowledge">
                                <subject v-model="tagName" :currentSubject="currentSubject" style="width:95%" @change='subjectChange'></subject> 
                                 <tag v-for="(item,index) in tagList" :key="index" :addable="true" @add="subjectChange(item)">{{item.tagName}}</tag>
                            </el-form-item>
                            <el-form-item label="关联知识点" prop="haveSubject">
                                <div class="subjectKuang">
                                    <el-tag :key="tag.name"  v-for="(tag,index) in question.knowledgeTagList" closable :disable-transitions="false"  @close="handleClose(index)">{{tag.tagName}}</el-tag>
                                </div>
                            </el-form-item> -->
                            <el-form-item label="关联知识点" prop="haveSubject">
                                <el-checkbox-group v-model="question.knowledgeTagList">
                                    <el-checkbox :label="item.tagName" v-for="(item,index) in tagList" :key="index" ></el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                        </el-col> 
                    </el-row>
                    <div class="form-item-title">
                        <span class="title-level">属性标签</span>
                    </div>
                    <el-row>
                        <el-col>
                            <el-radio-group v-model="question.difficulty" >
                                <el-radio :label="1">容易</el-radio>
                                <el-radio :label="3">一般</el-radio>
                                <el-radio :label="5">困难</el-radio>
                            </el-radio-group>
                        </el-col>
                    </el-row>
                </el-col>
                <el-col :span="12">
                    <div class="form-item-title">
                        <span class="title-level">题目预览</span>
                    </div>
                    <div class="preview" v-show="showPriview">
                        <div class="title">
                            <div class="title-preview" v-html="question.content"></div>
                            <div>
                                <img src="" alt="">
                            </div>
                        </div>
                        <div class="options">
                            <p :class="{'active':question.isCorrect==='Y'}"><i class="el-icon-circle-check"></i>正确</p>   
                            <p :class="{'active':question.isCorrect==='N'}"><i class="el-icon-circle-check"></i>错误</p>       
                        </div>
                        <div class="analyze">
                            <p>解析：</p>
                            <div v-html="question.analysis" class="analyze-content"></div>
                        </div>
                        <div class="knowledge-list">
                            <span>关联知识点：</span>
                                <!-- <el-tag  v-for="(item,index) in checkedTagList" :key="index">{{item.tagName}}</el-tag> -->
                                <el-tag  v-for="(item,index) in question.knowledgeTagList" :key="index">{{item.tagName?item.tagName:item}}</el-tag>
                        </div>
                        <div class="knowledge-list">
                            <span>难度：</span>
                            <el-tag>{{question.difficulty | showDifficultyTag}}</el-tag>
                        </div>                        
                    </div>
                    <div class="no-preview" v-show="!showPriview">
                    <div class="etm-preview">
                        <div class="empty">暂无题目预览</div>
                    </div>
                </div>
                </el-col>
            </el-row>
            <div class="form-item">
                <el-form-item class="footer">
                    <el-button @click="cancel">返回</el-button>
                    <el-button type="primary" @click="submitForm('ruleForm')" :disabled="optionsValidate" :loading="loadingBtn" v-loading="btnLoading">确认</el-button>
                </el-form-item>
            </div>
        </el-form> 

        <!-- 弹窗公式 -->
        <formula-dialog :clatex.sync="clatex" @getPicData="setDataPic"></formula-dialog>
        <!-- 弹窗公式 end -->

    </div>
</template>

<script>
import { mapGetters} from 'vuex';
// import tag from 'components/tag';
// import { createQuestion, getQuestionInfo, updateQuestion, fuzzyListTag } from 'api/standardBank';
import Tinymce from 'components/Tinymce';
import FormulaDialog from './formulaDialog';
import Subject from './subject';
import questionCheck from './addNewQuestionCheck';
export default {
    name: 'addNewQuestionContent',
    components: {questionCheck, Tinymce, FormulaDialog, Subject},
    data() {
        return {
            question: {
                content: '',
                knowledge: '',
                analysis: '',
                knowledgeList: [ 
                    {
                        id: 0,
                        name: '语文'
                    }
                ],
                knowledgeTagList: [], // 已有知识点
                isCorrect: '', // 正确答案
                difficulty: 3
            },
            fileList: [],
            clatex: false,
            loadingBtn: false,
            tinymceId2: 'tinymceId2', // 题目内容
            tinymceId3: 'tinymceId3', // 题目解析
            toolbar: ['p bold italic underline'],
            // toolbar: ['p | bold italic| alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent '],
            tagName: '',
            currentSubject: '',
            itemList: [],
            tagList: [], // 知识点列表
            optionsData: [],
            btnLoading: false,
            rules: {
                content: [
                     { required: true, message: '请输入题目内容', trigger: 'blur' }
                ]
            },
            contentTimer: null,
            maxonOff: true,
            type: null // 用来区分是题目正文还是解析解析内容  题目正文 = 1 , 解析内容 = 2
        }
    },
    created() {
        this.currentSubject = this.$route.params.summaryKey;
        this.getKnowledgeTag();
    },
    mounted() {
        if (this.isEdit()) {
            this.$emit('change', 'check');
            this.getQuestionContent()
        }
    },
    watch: {
        'question.content'(val) {            
            this.checkContentLength(val, 1);
        },
        'question.analysis'(val) {
            this.checkContentLength(val, 2);
        } 

    },
    computed: {
        ...mapGetters([
            'schoolId',
            'official'
        ]),
        isMultiselect() {
            let selectOptions = [];
            this.optionsData.forEach((item) => {
                if (item.isCorrect=='Y') {
                    selectOptions.push(item);
                }
            });
            return selectOptions;
        },
        showPriview() {
            return this.question.content.length > 0;
        },
        optionsValidate() {
            if (this.question.content.length > 0 && this.maxonOff) {
                return false
            }
            return true;
        }
        // checkedTagList() {
        //     let tag = null;
        //     let list = [];
        //     for (let i = 0;i<this.question.knowledgeTagList.length;i++) {
        //         tag = this.tagList.find(item => {
        //             return this.question.knowledgeTagList[i] === item.tagId
        //         })
        //         list.push({tagId: tag.tagId, tagName: tag.tagName});
        //     }
        //     return list;
        // }
    },
    methods: {
        isEdit() {
            var type = this.$route.params.type;
            var flag = this.$route.params.flag;
            if (type&&flag==1&&type==2) {
                return true;
            }
            return false;
        },

        getOptions(data) {
            this.optionsData = data;
        },

         // 判断题目和解析内容是否超过500字
        checkContentLength(val) {
            clearTimeout(this.contentTimer);
            this.contentTimer = setTimeout(() => {
                if (val) { 
                // 替换html标签 img标签
                    var content = val.replace(/<img[^>]*>/g, '').replace(/<(\w*)>(.*?)<\/\1>/g, function($1, $2, $3) {
                        return $3
                    });
                // 正则确定
                    var contentReg = /[a-z]+[\-\']?[a-z]*|[\u4e00-\u9fa5\w!@#$%^&*()（）、\-+\/,|\.，。！;；:：'"‘’“”【】？?]/ig;
                    content = content.match(contentReg);
                    if (content&&content.length > 500) {
                        this.$message.error('题目内容大于500字');
                        this.maxonOff = false
                    } else {
                        this.maxonOff = true;
                    }
                }
            }, 200)
        },

        // 获取本章节所有知识点
        getKnowledgeTag() {
            let chapterId = this.$route.params.chapterId;
            if (chapterId && this.currentSubject) {
                fuzzyListTag(this.currentSubject, chapterId).then(res => {
                    this.tagList = res.data.content;
                })
            }

        },

        // 选择知识点
        knowledgeChange() {
            console.log(1111111111);
        },
        // 删除知识点
        handleClose(index) {
            this.tagName = '';
            this.question.knowledgeTagList.splice(index, 1);
        },
        cancel() {
            this.question.content = '';
            this.$router.go(-1);
        },
        // 选择题答案
        questionAnswer(val) {
            console.log('va', val); 
            this.question.isCorrect = val;
        },
        // 确定
        submitForm(dataForm) {
            let currentSubject = this.$route.params.summaryKey;
            let importChapterId = this.$route.params.chapterId;
            let importChapterName = this.$route.params.chapterName;
            let questionContent = this.question.content;
            let tags = [];
            let questionType = 2;
            let questionId = this.$route.params.questionId;

          
            var json = {
                'content': this.question.isCorrect == 'Y' ? '1' : '0',
                'isCorrect': 'Y'
            };
            //  0 是错误  1是正确
            if (!this.isEdit()) {
                this.itemList= [json];
            } else {
                console.log(1212, 'edit');
                console.log(this.question.isCorrect);
                this.itemList[0].content = this.question.isCorrect == 'Y' ? '1' : '0';
                var jsonEdit = Object.assign({}, this.itemList[0]);
                this.itemList= [jsonEdit];
            }

            let items = this.itemList;

            console.log('item', items.length)

            this.question.knowledgeTagList.forEach((item) => {
                if (item.tagName) {
                    if (this.isEdit()) {
                        tags.push({'name': item.tagName});
    
                    } else {
                        tags.push(item.tagName);
                    }
                } else {
                    if (this.isEdit()) {
                        tags.push({'name': item});
    
                    } else {
                        tags.push(item);
                    }
                }
                // item.tagName?tags.push(item.tagName):tags.push(item);
            })

            this.$refs[dataForm].validate((valid) => {
                if (valid) {
                    let tempHtml = window.tinymce.get('tinymceId2').getContent({format: 'raw'});
                    if (tempHtml.indexOf('img') === -1) {
                        if (!window.tinymce.get('tinymceId2').getContent({format: 'text'}).trim()) {
                            this.$message('请输入题目内容');
                            return;
                        }
                        // if (window.tinymce.get('tinymceId').getContent({format: 'text'}).trim().length > 500) {
                        //     this.$message('判断题目内容不能大于500字');
                        //     return;
                        // }
                    }

                    if (this.question.isCorrect === '') {
                        this.$message('至少选择一个正确选项值');
                        return; 
                    }

                    this.$confirm('确认发布?', ' ', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: ' '
                    }).then(() => {
                        this.loading = true;
                        if (this.isEdit()) {
                            this._updateQuestion(currentSubject, questionId, questionContent, items, tags, importChapterId, questionType, this.question.difficulty, this.schoolId, this.question.analysis)
                        } else {
                            this._createQuestion(currentSubject, importChapterId, importChapterName, questionContent, questionType, items, tags, this.question.difficulty, this.schoolId, this.question.analysis, this.official);
                        }
                    })
                } else {
                    return false;
                }
            });
        },
        _createQuestion(currentSubject, importChapterId, importChapterName, questionContent, questionType, items, tags, difficult, source, soluationContent, official) {
            createQuestion(currentSubject, importChapterId, importChapterName, questionContent, questionType, items, tags, difficult, source, soluationContent, official).then(response => {
                this.loading = false;
                if (response.data.status == 200) {
                    this.$message.success(response.data.errorMsg);
                    this.$refs['ruleForm'].resetFields();
                    this.$store.dispatch('UpdateCache', true);
                    this.$router.push({'name': '标准题库'}); 
                    // this.$router.go(-1);
                } else {
                    this.$message.error(response.data.errorMsg);
                }
            }).catch(() => {
                this.loading = false;
            });
        },
        _updateQuestion(currentSubject, questionId, questionContent, items, tags, importChapterId, questionType, difficult, source, soluationContent) {
            updateQuestion(currentSubject, questionId, questionContent, items, tags, importChapterId, questionType, difficult, source, soluationContent).then(response => {
                this.loading = false;
                if (response.data.status == 200) {
                    this.$message.success(response.data.errorMsg);
                    this.$refs['ruleForm'].resetFields();
                    this.$store.dispatch('UpdateCache', true);
                    this.$router.push({'name': '标准题库'});
                } else {
                    this.$message.error(response.data.errorMsg);
                }
            }).catch(() => {
                this.loading = false;
            });
        },
        setDataPic(data) {
            if (this.type === 1) { // 题目内容
                this.$refs.tinymce2.execCommand(data.priviewImg);
                this.$refs.tinymce2.setContent(this.question.content);
                this.$refs.tinymce2.moveToBookmark(this.bookMark);
            } else { // 解析内容
                this.$refs.tinymce3.execCommand(data.priviewImg);
                this.$refs.tinymce3.setContent(this.question.analysis);
                this.$refs.tinymce3.moveToBookmark(this.bookMark);  
            }
        },
        // 题目内容插入公式
        insertFormula() {
            this.clatex = true;
            this.type = 1;
            this.bookMark = this.$refs.tinymce.getBookmark();
        },
        // 题目解析插入公式
        insertFormula1() {
            this.clatex = true;
            this.type = 2;
            this.bookMark1 = this.$refs.tinymce1.getBookmark();
        },
        subjectChange(val) {
            for (let i=0;i<this.question.knowledgeTagList.length;i++) {
                if (val.tagName == this.question.knowledgeTagList[i].tagName) {
                    this.$message({
                        type: 'warning',
                        message: '添加知识点重复'
                    });
                    return;
                }
            }
            if (val != '') {
                let tag = {
                    tagName: val.tagName,
                    tagId: val.tagId
                }
                this.question.knowledgeTagList.push(tag)
                this.tagName = '';
            }
        }, 
        // 获取内容题目
        getQuestionContent() {
            let questionId = this.$route.params.questionId;
            getQuestionInfo(this.currentSubject, questionId).then((res) => {
                console.log(res);
                if (res.data.status == 200) {
                    this.setContent(res.data.content);
                }
            })
        },
        setContent(data) {
            this.question.content = data.context;
            this.question.analysis = data.soluationContent?data.soluationContent:'';
            this.question.difficulty = data.difficult?Number(data.difficult):undefined;
            // this.question.knowledgeTagList = (data.tags === null ? [] : data.tags);
            if (data.tags) {
                for (let i=0;i<data.tags.length;i++) {
                    this.question.knowledgeTagList.push(data.tags[i].tagName);
                }
            } else {
                this.question.knowledgeTagList= [];
            }

            data.itemList.forEach((item) => {
                var json = {
                    'id': item.id,
                    'content': item.content,
                    'isCorrect': item.iscorrect
                }
                this.itemList = [json];
                console.log(this.itemList, json, 'yyyy');
                this.question.isCorrect = (item.content == '0' ? 'N' : 'Y');
            });
            this.$refs.setCheckList.setCheck(this.question.isCorrect);
        }
    },
    filters: {
        showDifficultyTag(val) {
            if (val === 1) {
                return '容易'
            } else if (val === 3) {
                return '一般'
            } else {
                return '困难'
            }
        },
        showTagName(val) {
            this.tagList.find(item => {
                return item.tagId === val
            }).tagName
        }
    }
}
</script>

<style lang="scss" scoped>
@import '../../../../styles/var.scss';
.upload{
    float: left;
}
.form-item-title{
    margin: 40px 0;
    font-size: 14px;
    color: #333;
    line-height: 14px;
    border-left: 4px solid #ff5e2c;
    text-indent: 16px;
}
.img-list{
    padding-top:15px;
    width:134px;
    height:88px;
    position: relative;
    img{
        width:100%;
        height:100%;   
    }
    i{
        position: absolute;
        right:-5px;
        top:10px;
        z-index: 2;
        color:#ccc;
        font-size:16px;
        cursor: pointer;
    }

}
.form-item-title:first-of-type{
    margin:20px 0;
}

.question-content{
    background:#fff;
    padding:10px 0 20px 20px;
    
}
.el-checkbox{
    margin-right:15px;
}
.el-tag{
    margin-left:10px;
    // margin-bottom: 10px;
    background:#f0f0f0;
    color:#444;
}
.form-item{
    padding-top:30px;
    text-align: center
}
.min-w {
    width: 600px;
}
.preview{
    padding-left:20px;
    width:600px;

    .title{
        font-size:14px; 
    }
    .title-preview {
        word-break: break-all;
    }
    .options{
        padding-top:15px;
        p{
            padding-bottom: 5px;
            font-size:14px;

            &.active{
            color: #07ba39; 
            }

            i{
                padding-right:5px;
            }
        }
    }
    .analyze{
        img{
            max-width:400px;
        }
    }
     .knowledge-list{ 
        float:left;
        padding-top: 15px;
        font-size:14px;
        .el-tag{
            margin-bottom: 10px;
        }
        
    }
}

</style>

